import xml.etree.ElementTree as ET

def createXmlfile():
    ''' 生成XML文件 '''
    new_xml=ET.Element("namelist")
    name =ET.SubElement(new_xml,"name",attrib={"china":"Yes"})
    name.text="张三"
    province = ET.SubElement(name, "province", attrib={"isxibei": "Yes"})
    province.text = "甘肃"
    Hometown = ET.SubElement(province, "Hometown", attrib={"istianshui": "Yes"})
    Hometown.text = "天水"
    age = ET.SubElement(name, "age", attrib={"old": "NO"})
    age.text="18"
    sex = ET.SubElement(name, "sex", attrib={"change": "Yes"})
    sex.text ="男"

    name = ET.SubElement(new_xml, "name", attrib={"china": "Yes"})
    name.text = "李四"
    age = ET.SubElement(name, "age", attrib={"old": "NO"})
    age.text = "30"
    sex = ET.SubElement(name, "sex", attrib={"change": "Yes"})
    sex.text="女"

    name = ET.SubElement(new_xml, "name", attrib={"china": "No"})
    name.text = "梦梦"
    age = ET.SubElement(name, "age", attrib={"old": "NO"})
    age.text = "18"
    sex = ET.SubElement(name, "sex", attrib={"change": "NO"})
    sex.text = "女"

    name = ET.SubElement(new_xml, "name", attrib={"china": "Yes"})
    name.text = "萌萌"
    age = ET.SubElement(name, "age", attrib={"old": "NO"})
    age.text = "30"
    sex = ET.SubElement(name, "sex", attrib={"change": "Yes"})
    sex.text= "女"

    et = ET.ElementTree(new_xml)
    et.write("practiceXml.xml",encoding="utf-8",xml_declaration=True)

def readXmlfile():
    ''' 遍历XML文件 '''
    tree = ET.parse("practiceXml.xml")
    root = tree.getroot()
    print(root.tag)
    for i in root:
        print(i.tag,i.text,i.attrib)
        for j in i:
            print(j.tag,j.text,j.attrib)

def updateXmlfile():
    '''修改xml的值、以及属性值'''
    tree = ET.parse("practiceXml.xml")
    root = tree.getroot()
    for k in root.iter('age'):
        new_age = int(k.text) +2
        k.text =str(new_age)
        k.set("Young","Yes")
    tree.write("practiceXml.xml")

def deleteXmlfile():
    '''删除XML文件中的内容、删除年龄大于40的人信息'''
    tree = ET.parse("practiceXml.xml")
    root = tree.getroot()
    for name in root.findall("name"):
        age = int (name.find("age").text)
        if age > 40:
            print("大于40岁的年龄%s," % age)
            root.remove(name)
    tree.write("practiceXml.xml")


createXmlfile()

readXmlfile()

updateXmlfile()

deleteXmlfile()